<template>
  <div class="register-container">
    <div class="register-left">
      <div class="financial-info">
        <h1 class="app-title">智能记账系统</h1>
        <p class="app-subtitle">轻松管理您的每一笔收支</p>
        <div class="features">
          <div class="feature-item">
            <el-icon class="feature-icon">
              <Wallet/>
            </el-icon>
            <span>收支明细一目了然</span>
          </div>
          <div class="feature-item">
            <el-icon class="feature-icon">
              <PieChart/>
            </el-icon>
            <span>数据统计图表展示</span>
          </div>
          <div class="feature-item">
            <el-icon class="feature-icon">
              <TrendCharts/>
            </el-icon>
            <span>财务趋势智能分析</span>
          </div>
        </div>
      </div>
    </div>

    <div class="register-right">
      <el-card class="register-box" shadow="always">
        <h2 class="register-title">创建新账户</h2>

        <el-form
            :model="registerForm"
            :rules="registerRules"
            ref="registerFormRef"
            @keyup.enter="handleRegister"
        >
          <el-form-item prop="username">
            <el-input
                v-model="registerForm.username"
                placeholder="请输入账户名"
                size="large"
                @blur="checkUsernameExists"
            >
              <template #prefix>
                <el-icon>
                  <UserFilled/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
            >
              <template #prefix>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                show-password
            >
              <template #prefix>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="phone">
            <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                size="large"
            >
              <template #prefix>
                <el-icon>
                  <Phone/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="email">
            <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱（选填）"
                size="large"
            >
              <template #prefix>
                <el-icon>
                  <Message/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="gender">
            <el-radio-group v-model="registerForm.gender" size="large">
              <el-radio label="1" border>男</el-radio>
              <el-radio label="0" border>女</el-radio>
              <el-radio label="2" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button
                :loading="loading"
                type="primary"
                size="large"
                @click="handleRegister"
                style="width: 100%"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>

          <div class="login-link">
            已有账号？
            <router-link to="/login">立即登录</router-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {UserFilled, Lock, Wallet, PieChart, TrendCharts, Phone, Message} from '@element-plus/icons-vue'
//import {useUserStore} from "@/stores/user.js";
import {userApi} from '@/api/user.js'

const router = useRouter()
const registerFormRef = ref()
const loading = ref(false)
const checkingUsername = ref(false)
const usernameExists = ref(false)

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  gender: '2' // 默认保密
})

const registerRules = {
  username: [
    {required: true, message: '请输入账户名', trigger: 'blur'},
    {min: 4, max: 20, message: '账户名长度应在4-20个字符之间', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (usernameExists.value) {
          callback(new Error('该账户名已存在，请更换其他账户名'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6个字符', trigger: 'blur'},
    {pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  email: [
    {pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  gender: [
    {required: false, trigger: 'change'}
  ]
}

// 检查账户名是否存在
const checkUsernameExists = async () => {
  if (!registerForm.username) return

  checkingUsername.value = true
  try {
    const response = await userApi.checkUsernameApi(registerForm.username)
    if (response.code === 500) {
      usernameExists.value = true
      ElMessage.warning('该账户名已存在，请更换其他账户名')
    } else if(response.code === 200){
      usernameExists.value = false
    }else{
      ElMessage.error(response.message || '检测失败请重新输入账户名')
    }
    registerFormRef.value.validateField('username')
  } catch (error) {
    console.error('Check username error:', error)
    usernameExists.value = false
    ElMessage.error('网络请求失败，请稍后重试')
  } finally {
    checkingUsername.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  const valid = await registerFormRef.value.validate().catch(() => false)
  if (!valid) return
  loading.value = true
  try {
    const registerData = {
      ...registerForm,
      // 不需要传递confirmPassword给后端
      confirmPassword: undefined
    }

    const response = await userApi.registerApi(registerData)
    if (response.code === 200) {
      ElMessage.success('注册成功！请登录')
      // 注册成功后，将用户信息存储到Pinia状态管理
      //userStore.setUserInfo(response.data)
      await router.push({path: '/login'})
    } else {
      ElMessage.error(response.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('Register error:', error)
    ElMessage.error('网络请求失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  padding: 20px;
}

.financial-info {
  max-width: 500px;
  text-align: center;
}

.app-title {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: bold;
}

.app-subtitle {
  font-size: 1.2rem;
  margin-bottom: 3rem;
  opacity: 0.9;
}

.features {
  text-align: left;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
  font-size: 1.1rem;
}

.feature-icon {
  font-size: 1.5rem;
  margin-right: 15px;
  color: #ffd700;
}

.register-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-box {
  width: 450px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #667eea;
  font-size: 1.8rem;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 单选框样式调整 */
.el-radio-group {
  display: flex;
  justify-content: space-around;
}

.el-radio {
  margin-right: 0 !important;
}

@media (max-width: 992px) {
  .register-left {
    display: none;
  }

  .register-container {
    justify-content: center;
  }
}
</style>